from abc import ABCMeta
import tornado
import time
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.escape
import threading

from database.models.DatabaseCommon import Session
from database.models.UserInfo import UserInfo
from database_resource import *
from SendWrap import *
import global_status
import logging


def QueryIfExist(dbcur, tableName, colom, value):
    sql = "select * from " + tableName + " where " + colom + " = ?"
    queryData = dbcur.execute(sql, (value,))
    return len(queryData.fetchall())


def CheckJsonKeys(obj, *keys):
    for i in keys:
        if not global_status.ai_ele_global_config['useAuth']:
            if i == 'username' or i == 'userpass':
                continue
        _ = obj[i]


def CheckAuth_1(username, userpass):
    if global_status.ai_ele_global_config['useAuth']:
        s = Session()
        c = s.query(UserInfo).filter_by(Name=str(username), Passwd=str(userpass)).count()
        if c != 1:
            raise Exception("Auth not ok")


def CheckAuth(ojson):
    if global_status.ai_ele_global_config['useAuth']:
        CheckAuth_1(ojson['username'], ojson['userpass'])


# device_listen_addr = 'http://127.0.0.1:60001/send_to_device'
device_listen_addr = 'http://192.168.0.106:60001/send_to_device'
